// 初始化地图
let map = L.map('map').setView([39.9042, 116.4074], 11); // 北京市中心
let baseLayer = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);

// 保存当前图层，用于清除
let currentLayers = [];

// 清除所有当前图层的函数
function clearLayers() {
    currentLayers.forEach(layer => map.removeLayer(layer));
    currentLayers = [];
}

// 描述文本更新函数
function updateDescription(text) {
    document.getElementById('scene-description').innerHTML = text;
}

// 1. 距离计算演示
function showDistance() {
    clearLayers();
    
    const description = `
        <strong>距离计算 (turf.distance)</strong><br>
        <strong>应用场景：</strong>
        <ul>
            <li>物流配送路线规划中计算两地之间的距离</li>
            <li>房地产应用中计算物业与关键设施（如地铁站、学校）的距离</li>
            <li>共享单车系统中找出用户附近的车辆</li>
            <li>定位应用中计算用户与目标地点的直线距离</li>
        </ul>
    `;
    updateDescription(description);
    
    // 示例：计算天安门和北京站之间的距离
    const point1 = turf.point([116.3912, 39.9055], { name: "天安门" });
    const point2 = turf.point([116.4278, 39.9047], { name: "北京站" });
    
    // 添加点到地图
    currentLayers.push(L.marker([39.9055, 116.3912]).bindPopup('天安门').addTo(map));
    currentLayers.push(L.marker([39.9047, 116.4278]).bindPopup('北京站').addTo(map));
    
    // 画线连接两点
    currentLayers.push(L.polyline([
        [39.9055, 116.3912],
        [39.9047, 116.4278]
    ], { color: 'blue' }).addTo(map));
    
    // 计算距离（单位：公里）
    const distance = turf.distance(point1, point2, { units: 'kilometers' });
    
    // 在线段中点显示距离信息
    const midpoint = turf.midpoint([116.3912, 39.9055], [116.4278, 39.9047]);
    currentLayers.push(L.marker([midpoint.geometry.coordinates[1], midpoint.geometry.coordinates[0]], {
        icon: L.divIcon({
            className: 'distance-label',
            html: `<div style="background:white;padding:5px;border-radius:5px;border:1px solid #777">${distance.toFixed(2)} 公里</div>`,
        })
    }).addTo(map));
    
    // 调整地图视图
    map.fitBounds([
        [39.9055, 116.3912],
        [39.9047, 116.4278]
    ], { padding: [50, 50] });
}

// 2. 面积计算演示
function showArea() {
    clearLayers();
    
    const description = `
        <strong>面积计算 (turf.area)</strong><br>
        <strong>应用场景：</strong>
        <ul>
            <li>土地规划和房地产应用中计算地块面积</li>
            <li>环保监测中计算森林覆盖、湖泊或其他自然区域的面积</li>
            <li>农业应用中计算农田面积估算产量</li>
            <li>城市规划中计算各功能区块面积占比</li>
        </ul>
    `;
    updateDescription(description);
    
    // 定义一个多边形（北京某区域）
    const polygon = turf.polygon([[
        [116.3867, 39.9288],
        [116.4188, 39.9300],
        [116.4207, 39.9062],
        [116.3846, 39.9053],
        [116.3867, 39.9288]
    ]], { name: "区域示例" });
    
    // 计算面积（平方米）
    const area = turf.area(polygon);
    
    // 在地图上显示多边形
    currentLayers.push(L.polygon([
        [39.9288, 116.3867],
        [39.9300, 116.4188],
        [39.9062, 116.4207],
        [39.9053, 116.3846],
        [39.9288, 116.3867]
    ], { color: 'green', fillOpacity: 0.4 }).bindPopup(`面积: ${(area / 1000000).toFixed(2)} 平方公里`).addTo(map));
    
    // 在多边形中心显示面积
    const center = turf.centroid(polygon);
    currentLayers.push(L.marker([center.geometry.coordinates[1], center.geometry.coordinates[0]], {
        icon: L.divIcon({
            className: 'area-label',
            html: `<div style="background:white;padding:5px;border-radius:5px;border:1px solid #777">${(area / 1000000).toFixed(2)} 平方公里</div>`,
        })
    }).addTo(map));
    
    // 调整地图视图
    map.fitBounds([
        [39.9288, 116.3867],
        [39.9300, 116.4188],
        [39.9062, 116.4207],
        [39.9053, 116.3846]
    ], { padding: [50, 50] });
}

// 3. 点包含判断演示
function showPointsWithin() {
    clearLayers();
    
    const description = `
        <strong>点包含判断 (turf.pointsWithin)</strong><br>
        <strong>应用场景：</strong>
        <ul>
            <li>商业分析中查找特定区域内的所有商店或客户</li>
            <li>房地产应用中寻找特定区域内的可用房产</li>
            <li>城市管理系统中查找区域内的公共设施（学校、医院等）</li>
            <li>事件管理系统中筛选特定区域内的事件</li>
        </ul>
    `;
    updateDescription(description);
    
    // 定义一个区域（故宫周边）
    const searchArea = turf.polygon([[
        [116.3800, 39.9180],
        [116.3800, 39.9000],
        [116.4100, 39.9000],
        [116.4100, 39.9180],
        [116.3800, 39.9180]
    ]]);
    
    // 定义一些兴趣点
    const points = turf.featureCollection([
        turf.point([116.3912, 39.9055], { name: "天安门" }),
        turf.point([116.3972, 39.9165], { name: "景山公园" }),
        turf.point([116.4027, 39.9087], { name: "故宫" }),
        turf.point([116.3845, 39.9054], { name: "国家大剧院" }),
        turf.point([116.4107, 39.9196], { name: "景山前街" }),
        turf.point([116.4278, 39.9047], { name: "北京站" })
    ]);
    
    // 查找区域内的点
    const ptsWithin = turf.pointsWithinPolygon(points, searchArea);
    
    // 在地图上显示区域
    currentLayers.push(L.polygon([
        [39.9180, 116.3800],
        [39.9000, 116.3800],
        [39.9000, 116.4100],
        [39.9180, 116.4100],
        [39.9180, 116.3800]
    ], { color: 'blue', fillOpacity: 0.2 }).bindPopup('搜索区域').addTo(map));
    
    // 显示所有点，区分区域内外
    points.features.forEach(pt => {
        const isInside = ptsWithin.features.some(p => 
            p.properties.name === pt.properties.name);
        const color = isInside ? 'green' : 'red';
        
        currentLayers.push(L.circleMarker(
            [pt.geometry.coordinates[1], pt.geometry.coordinates[0]],
            { color: color, radius: 7, fillOpacity: 0.7 }
        ).bindPopup(`${pt.properties.name} (${isInside ? '区域内' : '区域外'})`).addTo(map));
    });
    
    // 调整地图视图
    map.fitBounds([
        [39.9180, 116.3800],
        [39.9000, 116.3800],
        [39.9000, 116.4100],
        [39.9180, 116.4100]
    ], { padding: [50, 50] });
}

// 4. 最近点查找演示
function showNearestPoint() {
    clearLayers();
    
    const description = `
        <strong>最近点查找 (turf.nearest)</strong><br>
        <strong>应用场景：</strong>
        <ul>
            <li>导航应用中寻找最近的加油站、餐厅或医院</li>
            <li>打车应用中寻找离用户最近的可用车辆</li>
            <li>紧急服务调度中寻找最近的急救人员</li>
            <li>共享单车应用中寻找最近的可用单车</li>
        </ul>
    `;
    updateDescription(description);
    
    // 定义用户当前位置（天安门）
    const userLocation = turf.point([116.3912, 39.9055], { name: "当前位置" });
    
    // 定义一些兴趣点（如咖啡店）
    const coffeeShops = turf.featureCollection([
        turf.point([116.3972, 39.9165], { name: "咖啡店 A" }),
        turf.point([116.4027, 39.9087], { name: "咖啡店 B" }),
        turf.point([116.3845, 39.9054], { name: "咖啡店 C" }),
        turf.point([116.4107, 39.9196], { name: "咖啡店 D" }),
        turf.point([116.4017, 39.9047], { name: "咖啡店 E" })
    ]);
    
    // 查找最近的咖啡店
    const nearest = turf.nearestPoint(userLocation, coffeeShops);
    
    // 在地图上显示用户位置
    currentLayers.push(L.marker([39.9055, 116.3912], {
        icon: L.icon({
            iconUrl: 'https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-2x-blue.png',
            iconSize: [25, 41],
            iconAnchor: [12, 41]
        })
    }).bindPopup('您当前的位置').addTo(map));
    
    // 显示所有咖啡店，高亮最近的
    coffeeShops.features.forEach(shop => {
        const isNearest = shop.properties.name === nearest.properties.name;
        const iconColor = isNearest ? 'red' : 'green';
        const iconUrl = `https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-2x-${iconColor}.png`;
        
        currentLayers.push(L.marker(
            [shop.geometry.coordinates[1], shop.geometry.coordinates[0]],
            {
                icon: L.icon({
                    iconUrl: iconUrl,
                    iconSize: [25, 41],
                    iconAnchor: [12, 41]
                })
            }
        ).bindPopup(`${shop.properties.name} ${isNearest ? '(最近)' : ''}`).addTo(map));
        
        // 如果是最近的点，画一条连线
        if (isNearest) {
            currentLayers.push(L.polyline([
                [39.9055, 116.3912],
                [shop.geometry.coordinates[1], shop.geometry.coordinates[0]]
            ], { color: 'red', dashArray: '5, 5' }).addTo(map));
            
            // 计算并显示距离
            const distance = turf.distance(userLocation, shop, { units: 'kilometers' });
            const midpoint = turf.midpoint(
                [116.3912, 39.9055],
                [shop.geometry.coordinates[0], shop.geometry.coordinates[1]]
            );
            
            currentLayers.push(L.marker([midpoint.geometry.coordinates[1], midpoint.geometry.coordinates[0]], {
                icon: L.divIcon({
                    className: 'distance-label',
                    html: `<div style="background:white;padding:5px;border-radius:5px;border:1px solid #777">${distance.toFixed(2)} 公里</div>`,
                })
            }).addTo(map));
        }
    });
    
    // 调整地图视图
    map.fitBounds([
        [39.9055, 116.3912],
        [39.9196, 116.4107]
    ], { padding: [50, 50] });
}

// 5. 缓冲区生成演示
function showBuffer() {
    clearLayers();
    
    const description = `
        <strong>缓冲区生成 (turf.buffer)</strong><br>
        <strong>应用场景：</strong>
        <ul>
            <li>环境影响评估中分析污染源周围的影响范围</li>
            <li>城市规划中确定设施服务覆盖范围（如学校、医院服务半径）</li>
            <li>通信基站覆盖范围分析</li>
            <li>生态保护区边界缓冲区设定</li>
            <li>零售店铺选址时分析竞争对手覆盖范围</li>
        </ul>
    `;
    updateDescription(description);
    
    // 定义一个点（如地铁站）
    const metroStation = turf.point([116.4027, 39.9087], { name: "地铁站" });
    
    // 生成不同半径的缓冲区（步行距离）
    const buffer500m = turf.buffer(metroStation, 0.5, { units: 'kilometers' });
    const buffer1km = turf.buffer(metroStation, 1, { units: 'kilometers' });
    
    // 在地图上显示地铁站
    currentLayers.push(L.marker([39.9087, 116.4027], {
        icon: L.icon({
            iconUrl: 'https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-2x-red.png',
            iconSize: [25, 41],
            iconAnchor: [12, 41]
        })
    }).bindPopup('地铁站').addTo(map));
    
    // 显示缓冲区
    const buffer500mCoords = buffer500m.geometry.coordinates[0].map(coord => [coord[1], coord[0]]);
    const buffer1kmCoords = buffer1km.geometry.coordinates[0].map(coord => [coord[1], coord[0]]);
    
    currentLayers.push(L.polygon(buffer1kmCoords, { 
        color: '#ff9800', 
        fillOpacity: 0.2,
        weight: 1
    }).bindPopup('1公里缓冲区 (约15分钟步行)').addTo(map));
    
    currentLayers.push(L.polygon(buffer500mCoords, {
        color: '#f44336',
        fillOpacity: 0.3,
        weight: 1
    }).bindPopup('500米缓冲区 (约7分钟步行)').addTo(map));
    
    // 添加一些在缓冲区内的兴趣点
    const pois = [
        { name: "咖啡店", coord: [116.4047, 39.9107] },
        { name: "超市", coord: [116.4067, 39.9047] },
        { name: "书店", coord: [116.4007, 39.9137] },
        { name: "银行", coord: [116.3987, 39.9087] },
        { name: "餐厅", coord: [116.4127, 39.9087] }
    ];
    
    pois.forEach(poi => {
        const pt = turf.point(poi.coord);
        const in500m = turf.booleanPointInPolygon(pt, buffer500m);
        const in1km = turf.booleanPointInPolygon(pt, buffer1km);
        
        let color;
        let popupText = poi.name;
        
        if (in500m) {
            color = 'green';
            popupText += " (步行7分钟内)";
        } else if (in1km) {
            color = 'orange';
            popupText += " (步行15分钟内)";
        } else {
            color = 'gray';
            popupText += " (超出步行范围)";
        }
        
        currentLayers.push(L.circleMarker([poi.coord[1], poi.coord[0]], {
            color: color,
            fillColor: color,
            radius: 6,
            fillOpacity: 0.7,
            weight: 1
        }).bindPopup(popupText).addTo(map));
    });
    
    // 调整地图视图以包含最大缓冲区
    map.fitBounds(buffer1kmCoords, { padding: [50, 50] });
}

// 6. 相交分析演示
function showIntersect() {
    clearLayers();
    
    const description = `
        <strong>相交分析 (turf.intersect)</strong><br>
        <strong>应用场景：</strong>
        <ul>
            <li>城市规划中计算不同行政区域的重叠部分</li>
            <li>环境管理中确定洪水区域与居住区的交叉区域</li>
            <li>资源管理中判断自然保护区与采矿区的重叠</li>
            <li>农业分析中确定特定土壤类型与作物分布的交叉区域</li>
        </ul>
    `;
    updateDescription(description);
    
    // 定义两个多边形
    const poly1 = turf.polygon([[
        [116.3800, 39.9150],
        [116.4050, 39.9150],
        [116.4050, 39.9000],
        [116.3800, 39.9000],
        [116.3800, 39.9150]
    ]], { name: "居住区" });
    
    const poly2 = turf.polygon([[
        [116.3900, 39.9200],
        [116.4200, 39.9200],
        [116.4200, 39.9050],
        [116.3900, 39.9050],
        [116.3900, 39.9200]
    ]], { name: "商业区" });
    
    // 计算相交区域
    const intersection = turf.intersect(poly1, poly2);
    
    // 在地图上显示两个多边形和它们的交集
    currentLayers.push(L.polygon([
        [39.9150, 116.3800],
        [39.9150, 116.4050],
        [39.9000, 116.4050],
        [39.9000, 116.3800],
        [39.9150, 116.3800]
    ], { color: 'blue', fillOpacity: 0.3, weight: 2 }).bindPopup('居住区').addTo(map));
    
    currentLayers.push(L.polygon([
        [39.9200, 116.3900],
        [39.9200, 116.4200],
        [39.9050, 116.4200],
        [39.9050, 116.3900],
        [39.9200, 116.3900]
    ], { color: 'red', fillOpacity: 0.3, weight: 2 }).bindPopup('商业区').addTo(map));
    
    // 确保 intersection 存在
    if (intersection && intersection.geometry) {
        const intersectionCoords = intersection.geometry.coordinates[0].map(coord => [coord[1], coord[0]]);
        
        currentLayers.push(L.polygon(intersectionCoords, {
            color: 'purple',
            fillOpacity: 0.6,
            weight: 2
        }).bindPopup('居住商业混合区').addTo(map));
        
        // 计算交集面积
        const areaIntersect = turf.area(intersection);
        const areaPoly1 = turf.area(poly1);
        const areaPoly2 = turf.area(poly2);
        
        // 在交集中心显示面积信息
        const centerIntersect = turf.centroid(intersection);
        currentLayers.push(L.marker([centerIntersect.geometry.coordinates[1], centerIntersect.geometry.coordinates[0]], {
            icon: L.divIcon({
                className: 'area-label',
                html: `<div style="background:white;padding:5px;border-radius:5px;border:1px solid #777">
                      交叉面积: ${(areaIntersect / 1000000).toFixed(2)} 平方公里<br>
                      占居住区: ${((areaIntersect / areaPoly1) * 100).toFixed(1)}%<br>
                      占商业区: ${((areaIntersect / areaPoly2) * 100).toFixed(1)}%
                      </div>`,
            })
        }).addTo(map));
    }
    
    // 调整地图视图
    map.fitBounds([
        [39.9200, 116.3800],
        [39.9000, 116.4200]
    ], { padding: [50, 50] });
}

// 7. 合并多边形演示
function showUnion() {
    clearLayers();
    
    const description = `
        <strong>合并多边形 (turf.union)</strong><br>
        <strong>应用场景：</strong>
        <ul>
            <li>行政区划整合，合并相邻区域</li>
            <li>土地规划中合并相邻地块</li>
            <li>销售区域优化，合并重叠的销售区域</li>
            <li>自然保护区扩张规划，将多个区域合并为一个大保护区</li>
        </ul>
    `;
    updateDescription(description);
    
    // 定义几个多边形（如不同的行政区）
    const district1 = turf.polygon([[
        [116.3800, 39.9150],
        [116.4000, 39.9150],
        [116.4000, 39.9000],
        [116.3800, 39.9000],
        [116.3800, 39.9150]
    ]], { name: "区域A" });
    
    const district2 = turf.polygon([[
        [116.4000, 39.9150],
        [116.4200, 39.9150],
        [116.4200, 39.9000],
        [116.4000, 39.9000],
        [116.4000, 39.9150]
    ]], { name: "区域B" });
    
    const district3 = turf.polygon([[
        [116.3900, 39.9000],
        [116.4100, 39.9000],
        [116.4100, 39.8900],
        [116.3900, 39.8900],
        [116.3900, 39.9000]
    ]], { name: "区域C" });
    
    // 合并多边形
    const union1 = turf.union(district1, district2);
    const unionAll = turf.union(union1, district3);
    
    // 显示原始多边形
    currentLayers.push(L.polygon([
        [39.9150, 116.3800],
        [39.9150, 116.4000],
        [39.9000, 116.4000],
        [39.9000, 116.3800],
        [39.9150, 116.3800]
    ], { color: '#ff5722', fillOpacity: 0.4, weight: 2 }).bindPopup('区域A').addTo(map));
    
    currentLayers.push(L.polygon([
        [39.9150, 116.4000],
        [39.9150, 116.4200],
        [39.9000, 116.4200],
        [39.9000, 116.4000],
        [39.9150, 116.4000]
    ], { color: '#4caf50', fillOpacity: 0.4, weight: 2 }).bindPopup('区域B').addTo(map));
    
    currentLayers.push(L.polygon([
        [39.9000, 116.3900],
        [39.9000, 116.4100],
        [39.8900, 116.4100],
        [39.8900, 116.3900],
        [39.9000, 116.3900]
    ], { color: '#2196f3', fillOpacity: 0.4, weight: 2 }).bindPopup('区域C').addTo(map));
    
    // 显示合并后的多边形（带虚线边框）
    if (unionAll && unionAll.geometry) {
        // 处理多多边形情况
        let mergedPolygonCoords;
        if (unionAll.geometry.type === 'Polygon') {
            mergedPolygonCoords = [unionAll.geometry.coordinates[0].map(coord => [coord[1], coord[0]])];
        } else if (unionAll.geometry.type === 'MultiPolygon') {
            mergedPolygonCoords = unionAll.geometry.coordinates.map(poly => 
                poly[0].map(coord => [coord[1], coord[0]])
            );
        }
        
        mergedPolygonCoords.forEach((coords, i) => {
            currentLayers.push(L.polygon(coords, {
                color: '#9c27b0',
                fillOpacity: 0.1,
                weight: 2,
                dashArray: '5, 5'
            }).bindPopup('合并后的区域').addTo(map));
        });
        
        // 计算合并前后的面积
        const area1 = turf.area(district1);
        const area2 = turf.area(district2);
        const area3 = turf.area(district3);
        const totalAreaUnion = turf.area(unionAll);
        
        // 显示面积信息
        const center = turf.centroid(unionAll);
        currentLayers.push(L.marker([center.geometry.coordinates[1], center.geometry.coordinates[0]], {
            icon: L.divIcon({
                className: 'area-label',
                html: `<div style="background:white;padding:5px;border-radius:5px;border:1px solid #777">
                      原始总面积: ${((area1 + area2 + area3) / 1000000).toFixed(2)} 平方公里<br>
                      合并后面积: ${(totalAreaUnion / 1000000).toFixed(2)} 平方公里<br>
                      重叠面积: ${(((area1 + area2 + area3) - totalAreaUnion) / 1000000).toFixed(2)} 平方公里
                      </div>`,
            })
        }).addTo(map));
    }
    
    // 调整地图视图
    map.fitBounds([
        [39.9150, 116.3800],
        [39.8900, 116.4200]
    ], { padding: [50, 50] });
}

// 8. 点聚合演示
function showCluster() {
    clearLayers();
    
    const description = `
        <strong>点聚合 (turf.clustersKmeans)</strong><br>
        <strong>应用场景：</strong>
        <ul>
            <li>客户分布分析，将客户按地理位置聚类</li>
            <li>犯罪热点分析，识别犯罪事件集中的区域</li>
            <li>零售店铺选址，分析现有店铺分布模式</li>
            <li>物流配送中心选址，基于配送地点分布</li>
        </ul>
    `;
    updateDescription(description);
    
    // 生成一些随机点（如客户位置）
    const points = turf.randomPoint(30, { bbox: [116.3700, 39.8900, 116.4300, 39.9300] });
    
    // 添加属性
    points.features.forEach((pt, i) => {
        pt.properties.id = i;
        pt.properties.name = `客户 ${i+1}`;
    });
    
    // 使用KMeans进行聚类（分为4个簇）
    const clustered = turf.clustersKmeans(points, { numberOfClusters: 4 });
    
    // 获取各个簇
    const clusterGroups = {};
    clustered.features.forEach(pt => {
        const cluster = pt.properties.cluster;
        if (!clusterGroups[cluster]) {
            clusterGroups[cluster] = [];
        }
        clusterGroups[cluster].push(pt);
    });
    
    // 定义簇的颜色
    const clusterColors = ['#e53935', '#43a047', '#1e88e5', '#fb8c00'];
    
    // 在地图上显示聚类结果
    Object.keys(clusterGroups).forEach((cluster, index) => {
        const color = clusterColors[index % clusterColors.length];
        const points = clusterGroups[cluster];
        
        // 为每个簇创建中心点
        const pointCoords = points.map(pt => pt.geometry.coordinates);
        const pointsFC = turf.featureCollection(points);
        const centerPoint = turf.center(pointsFC);
        
        // 显示每个簇中的点
        points.forEach(pt => {
            currentLayers.push(L.circleMarker(
                [pt.geometry.coordinates[1], pt.geometry.coordinates[0]],
                {
                    color: color,
                    fillColor: color,
                    radius: 5,
                    weight: 1,
                    opacity: 0.8,
                    fillOpacity: 0.6
                }
            ).bindPopup(`${pt.properties.name} (簇 ${cluster})`).addTo(map));
        });
        
        // 显示簇中心
        currentLayers.push(L.circleMarker(
            [centerPoint.geometry.coordinates[1], centerPoint.geometry.coordinates[0]],
            {
                color: 'black',
                fillColor: color,
                radius: 10,
                weight: 2,
                opacity: 1,
                fillOpacity: 0.8
            }
        ).bindPopup(`簇 ${cluster} 中心 (包含 ${points.length} 个客户)`).addTo(map));
        
        // 添加从每个点到中心的线，表示属于该簇
        points.forEach(pt => {
            currentLayers.push(L.polyline([
                [pt.geometry.coordinates[1], pt.geometry.coordinates[0]],
                [centerPoint.geometry.coordinates[1], centerPoint.geometry.coordinates[0]]
            ], { 
                color: color, 
                weight: 1, 
                opacity: 0.3,
                dashArray: '3, 3'
            }).addTo(map));
        });
    });
    
    // 调整地图视图
    map.fitBounds([
        [39.8900, 116.3700],
        [39.9300, 116.4300]
    ], { padding: [50, 50] });
}

// 9. 线简化演示
function showSimplify() {
    clearLayers();
    
    const description = `
        <strong>线简化 (turf.simplify)</strong><br>
        <strong>应用场景：</strong>
        <ul>
            <li>地图缩放时简化复杂地理特征（如海岸线、河流）以提高渲染性能</li>
            <li>移动设备上减少地图数据大小，提高加载速度</li>
            <li>生成不同精度的地理数据用于不同比例尺地图</li>
            <li>简化GPS轨迹数据，去除冗余点</li>
        </ul>
    `;
    updateDescription(description);
    
    // 创建一条复杂的线路（如河流或GPS轨迹）
    const complexLine = turf.lineString([
        [116.3800, 39.9200],
        [116.3830, 39.9190],
        [116.3850, 39.9195],
        [116.3870, 39.9180],
        [116.3890, 39.9185],
        [116.3910, 39.9170],
        [116.3920, 39.9175],
        [116.3940, 39.9165],
        [116.3960, 39.9170],
        [116.3980, 39.9160],
        [116.3990, 39.9165],
        [116.4010, 39.9155],
        [116.4030, 39.9160],
        [116.4050, 39.9150],
        [116.4070, 39.9155],
        [116.4090, 39.9145],
        [116.4100, 39.9150],
        [116.4120, 39.9140],
        [116.4140, 39.9145],
        [116.4160, 39.9135],
        [116.4180, 39.9140],
        [116.4200, 39.9130],
    ]);
    
    // 应用不同程度的简化
    const simplifiedLow = turf.simplify(complexLine, { tolerance: 0.001, highQuality: true });
    const simplifiedHigh = turf.simplify(complexLine, { tolerance: 0.003, highQuality: true });
    
    // 转换为 Leaflet 可用的坐标格式
    const complexCoords = complexLine.geometry.coordinates.map(coord => [coord[1], coord[0]]);
    const simplifiedLowCoords = simplifiedLow.geometry.coordinates.map(coord => [coord[1], coord[0]]);
    const simplifiedHighCoords = simplifiedHigh.geometry.coordinates.map(coord => [coord[1], coord[0]]);
    
    // 显示原始线
    currentLayers.push(L.polyline(complexCoords, { 
        color: '#3f51b5', 
        weight: 4,
        opacity: 0.8
    }).bindPopup(`原始线: ${complexLine.geometry.coordinates.length} 个点`).addTo(map));
    
    // 显示每个点
    complexLine.geometry.coordinates.forEach((coord, i) => {
        currentLayers.push(L.circleMarker([coord[1], coord[0]], {
            color: '#3f51b5',
            radius: 3,
            fillOpacity: 1
        }).bindPopup(`原始点 ${i+1}`).addTo(map));
    });
    
    // 显示低度简化的线
    currentLayers.push(L.polyline(simplifiedLowCoords, { 
        color: '#ff9800', 
        weight: 3,
        opacity: 0.8,
        dashArray: '5, 5'
    }).bindPopup(`低度简化: ${simplifiedLow.geometry.coordinates.length} 个点`).addTo(map));
    
    // 显示高度简化的线
    currentLayers.push(L.polyline(simplifiedHighCoords, { 
        color: '#f44336', 
        weight: 2,
        opacity: 0.8,
        dashArray: '10, 10'
    }).bindPopup(`高度简化: ${simplifiedHigh.geometry.coordinates.length} 个点`).addTo(map));
    
    // 添加图例
    const legend = L.control({ position: 'bottomright' });
    legend.onAdd = function(map) {
        const div = L.DomUtil.create('div', 'legend');
        div.innerHTML = `
            <div style="background:white;padding:10px;border-radius:5px;border:1px solid #777">
                <div><span style="display:inline-block;width:20px;height:4px;background:#3f51b5;"></span> 原始线 (${complexLine.geometry.coordinates.length} 点)</div>
                <div><span style="display:inline-block;width:20px;height:3px;background:#ff9800;margin-top:5px"></span> 低度简化 (${simplifiedLow.geometry.coordinates.length} 点)</div>
                <div><span style="display:inline-block;width:20px;height:2px;background:#f44336;margin-top:5px"></span> 高度简化 (${simplifiedHigh.geometry.coordinates.length} 点)</div>
            </div>
        `;
        return div;
    };
    
    legend.addTo(map);
    currentLayers.push(legend);
    
    // 调整地图视图
    map.fitBounds(complexCoords, { padding: [50, 50] });
}

// 10. 六边形格网演示
function showHexGrid() {
    clearLayers();
    
    const description = `
        <strong>六边形格网 (turf.hexGrid)</strong><br>
        <strong>应用场景：</strong>
        <ul>
            <li>人口密度分析，按六边形网格显示人口分布</li>
            <li>商业分析，展示销售点密度和市场覆盖情况</li>
            <li>环境监测，以网格形式展示污染浓度分布</li>
            <li>选举数据可视化，展示不同区域的投票倾向</li>
            <li>蜂窝通信网络覆盖分析</li>
        </ul>
    `;
    updateDescription(description);
    
    // 定义一个区域范围（北京市中心一部分）
    const bbox = [116.3800, 39.9000, 116.4200, 39.9300];
    
    // 创建六边形网格
    const hexgrid = turf.hexGrid(bbox, 0.5, { units: 'kilometers' });
    
    // 生成一些随机点（如商店位置）
    const points = turf.randomPoint(40, { bbox: bbox });
    
    // 计算每个六边形中的点数
    hexgrid.features.forEach(hex => {
        let pointsInside = 0;
        points.features.forEach(pt => {
            if (turf.booleanPointInPolygon(pt, hex)) {
                pointsInside++;
            }
        });
        hex.properties.pointCount = pointsInside;
    });
    
    // 显示六边形网格
    hexgrid.features.forEach(hex => {
        const coords = hex.geometry.coordinates[0].map(coord => [coord[1], coord[0]]);
        const count = hex.properties.pointCount;
        
        // 根据点的数量设置颜色
        let color = '#ffffff';
        let opacity = 0;
        
        if (count > 0) {
            if (count <= 1) { color = '#c8e6c9'; opacity = 0.5; }
            else if (count <= 2) { color = '#81c784'; opacity = 0.6; }
            else if (count <= 3) { color = '#4caf50'; opacity = 0.7; }
            else if (count <= 4) { color = '#2e7d32'; opacity = 0.8; }
            else { color = '#1b5e20'; opacity = 0.9; }
        }
        
        currentLayers.push(L.polygon(coords, {
            color: '#666',
            weight: 1,
            fillColor: color,
            fillOpacity: opacity
        }).bindPopup(`商店数量: ${count}`).addTo(map));
    });
    
    // 显示点
    points.features.forEach((pt, i) => {
        currentLayers.push(L.circleMarker(
            [pt.geometry.coordinates[1], pt.geometry.coordinates[0]],
            {
                color: '#e91e63',
                fillColor: '#e91e63',
                radius: 4,
                weight: 1,
                opacity: 0.8,
                fillOpacity: 0.6
            }
        ).bindPopup(`商店 ${i+1}`).addTo(map));
    });
    
    // 添加图例
    const legend = L.control({ position: 'bottomright' });
    legend.onAdd = function(map) {
        const div = L.DomUtil.create('div', 'legend');
        div.innerHTML = `
            <div style="background:white;padding:10px;border-radius:5px;border:1px solid #777">
                <h4 style="margin:0 0 5px 0">商店密度</h4>
                <div><span style="display:inline-block;width:15px;height:15px;background:#c8e6c9;margin-right:5px"></span> 1家</div>
                <div><span style="display:inline-block;width:15px;height:15px;background:#81c784;margin-right:5px"></span> 2家</div>
                <div><span style="display:inline-block;width:15px;height:15px;background:#4caf50;margin-right:5px"></span> 3家</div>
                <div><span style="display:inline-block;width:15px;height:15px;background:#2e7d32;margin-right:5px"></span> 4家</div>
                <div><span style="display:inline-block;width:15px;height:15px;background:#1b5e20;margin-right:5px"></span> 5家以上</div>
                <div><span style="display:inline-block;width:15px;height:15px;background:#e91e63;border-radius:50%;margin-right:5px"></span> 商店位置</div>
            </div>
        `;
        return div;
    };
    
    legend.addTo(map);
    currentLayers.push(legend);
    
    // 调整地图视图
    map.fitBounds([
        [39.9000, 116.3800],
        [39.9300, 116.4200]
    ], { padding: [50, 50] });
}

// 初始化地图
window.onload = function() {
    // 默认显示一个欢迎信息
    const welcomeLayer = L.popup()
        .setLatLng([39.9042, 116.4074])
        .setContent('<h3>欢迎使用 Turf.js 常用 API 演示</h3><p>请点击左侧菜单查看不同功能的演示</p>')
        .openOn(map);
    
    currentLayers.push(welcomeLayer);
    
    // 设置初始描述
    updateDescription(`
        <strong>欢迎使用 Turf.js 常用 API 演示!</strong><br>
        Turf.js 是一个强大的地理空间分析库，可以在浏览器和 Node.js 环境中进行复杂的地理计算。<br><br>
        本演示包含了 Turf.js 中最常用的 10 个 API 的实际应用场景，点击左侧按钮查看具体示例。<br><br>
        每个示例都展示了该 API 在实际项目中的应用场景和用法。
    `);
};
